package com.bookseek.xreader.service;

import com.bookseek.xreader.params.BookParams;
import com.bookseek.xreader.params.BookSearchParams;
import com.bookseek.xreader.po.THisPo;
import com.bookseek.xreader.service.dk.BdocService;
import com.bookseek.xreader.service.dk.THisService;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.utils.OkHttpUtils;
import com.bookseek.xreader.vo.BookListItemVo;
import com.bookseek.xreader.vo.FtsBdocVo;
import com.bookseek.xreader.vo.HttpRetVo;
import com.bookseek.xreader.vo.mock.ChapterBcontDetailVo;
import com.bookseek.xreader.vo.mock.TBookChapterVo;
import com.bookseek.xreader.vo.mock.TBookInfoVo;

import org.greenrobot.greendao.DaoLog;

import java.util.List;

public class NbSqlQueryManager {
    private static NbSqlQueryManager instance;

    private NbSqlQueryManager(){

    }

    public static NbSqlQueryManager getInstance(){
        if(instance == null){
            synchronized (NbSqlQueryManager.class){
                if(instance == null){
                    instance = new NbSqlQueryManager();
                }
            }
        }
        return instance;
    }

    public void queryBdocByBtype(BookSearchParams params, OkHttpUtils.SqlCallback<List<BookListItemVo>> callBack){
        DLog.info("params===>",OkHttpUtils.gson.toJson(params));
        OkHttpUtils  okHttpUtils =  OkHttpUtils.getInstance();
        okHttpUtils.getThreadPool().execute(()->{
            List<BookListItemVo> datas = BdocService.getInstance().queryByBtype(params);
            okHttpUtils.getMainHandler().post(()->{
                if(callBack != null){
                    callBack.onSuccess(datas);
                }
            });
        });
    }

    /**
     * 获取文本
     * @param cvs
     * @param callback
     */
    public void getTextJsonAsync(List<String> cvs,OkHttpUtils.SqlCallback<HttpRetVo> callback){
        OkHttpUtils  okHttpUtils =  OkHttpUtils.getInstance();
        okHttpUtils.getThreadPool().execute(()->{
            boolean haveOk = false;
            for(String api : cvs){
              HttpRetVo retVo = okHttpUtils.getSyncStr(api);
              if(retVo.success && JkhlUtils.notBlank(retVo.text)){
                  okHttpUtils.getMainHandler().post(()->{
                      if(callback != null){
                          callback.onSuccess(retVo);
                      }
                  });
                  haveOk = true;
                  break;
              }
            }
            if(!haveOk){
                if(callback != null){
                    DLog.info("CVS=>",cvs);
                    callback.onError(new RuntimeException("未找到可用cvs 服务"));
                }
            }
        });
    }

    public void getTBookChapterContentAsync(TBookChapterVo chapterVo, OkHttpUtils.SqlCallback<ChapterBcontDetailVo> callback){
        if(callback == null){
            return;
        }
        List<String> validCvs = JkhlUtils.validCvs(chapterVo.cvs);
        DLog.info("title=>",chapterVo.btitle," id=",chapterVo.id," validCvs=",validCvs);
        getTextJsonAsync(validCvs, new OkHttpUtils.SqlCallback<HttpRetVo>() {
            @Override
            public void onSuccess(HttpRetVo result) {
                if(JkhlUtils.notBlank(result.text)){
                    try{
                        ChapterBcontDetailVo infoVo = OkHttpUtils.gson.fromJson(result.text,ChapterBcontDetailVo.class);
                        if(callback != null ){
                            callback.onSuccess(infoVo);
                        }
                    } catch (Exception e) {
                        callback.onError(e);
                    }

                }
            }

            @Override
            public void onError(Exception e) {
                    callback.onError(e);
            }
        });
    }
    public void getTBookInfoAsync(BookParams params,OkHttpUtils.SqlCallback<TBookInfoVo> callback){
        if(callback == null){
            return;
        }
        //书籍基本信息
        FtsBdocVo bdocVo = BdocService.getInstance().getByRowid(params.cid);
        getTextJsonAsync(bdocVo.bphkCvs, new OkHttpUtils.SqlCallback<HttpRetVo>() {
            @Override
            public void onSuccess(HttpRetVo result) {
                if(JkhlUtils.notBlank(result.text) && callback != null){
                    try{
                        //章节信息
                        TBookInfoVo infoVo = OkHttpUtils.gson.fromJson(result.text,TBookInfoVo.class);
                        if(callback != null ){
                            //获取典籍历史阅读信息
                            THisPo lastReadHisPo = THisService.getInstance().getBookLastReadInfo(params.cid);
                            DLog.info("阅读位置信息===》",OkHttpUtils.gson.toJson(lastReadHisPo));
                            if(lastReadHisPo != null){
                                infoVo.nowReadChapterId = lastReadHisPo.cid;
                            }else{
                                //无历史记录 默认第一章
                                infoVo.nowReadChapterId = infoVo.chapters != null ? infoVo.chapters.stream().map(d->d.id).findFirst().orElse(null) : null;
                            }
                            callback.onSuccess(infoVo);
                        }
                    } catch (Exception e) {
                        callback.onError(e);
                    }

                }
            }

            @Override
            public void onError(Exception e) {
                callback.onError(e);
            }
        });
    }

    public void saveDianjiReadInfo(THisPo po){
        po.tm = System.currentTimeMillis()/1000;
        OkHttpUtils  okHttpUtils =  OkHttpUtils.getInstance();
        okHttpUtils.getThreadPool().execute(()->{
            THisService.getInstance().saveDianJiHis(po);
        });
    }








}
